package practise.alogrithm.hundredInterviewQuestions.secondTime;

/**
 * Created by Richard on 7/26/2014.
 */
public class RevertWordsInString {
    public String revert(String str){
        char[] characters = str.toCharArray();
        revertWord(characters,0, characters.length-1);// reference transfer, not value
        int start =0;
        for(int index=0; index<characters.length;index++){
            if(characters[index]==' '){
                revertWord(characters,start,index-1);
                start=index+1;

            }
        }
        revertWord(characters,start,characters.length-1);
        return new String(characters);
    }

    private char[] revertWord(char[] whole, int start, int end){//note there, we transfer the array, then it is the address, we don't need to copy it again

        while(start<end){
            char temp = whole[start];
            whole[start] = whole[end];
            whole[end] = temp;
            start++;
            end--;
        }
        return whole;
    }

    public static void main(String[] args){
        RevertWordsInString revertWordsInString = new RevertWordsInString();
        System.out.print("Result:"+revertWordsInString.revert("abc def hig."));
    }
}
